package com.maxd.controller.commodityCoupon;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.CommodityCoupon;
import com.maxd.model.CommonInfo;
import com.maxd.respository.common.CommonRepository;
import com.maxd.utils.AmountCalUtils;
import com.maxd.utils.Config;
import com.maxd.utils.HttpClient;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkGoodsSearchRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsSearchResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.io.UnsupportedEncodingException;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @author fang
 * @date 2020/8/24
 */
@RestController
@Api(value = "淘宝京东拼多多商品整合", tags = {"淘宝京东拼多多商品整合"})
@RequestMapping(value = "/commodityCoupon")
public class CommodityCouponController {

    @Autowired
    private CommonRepository commonRepository;


    @RequestMapping(value = "/selectCommodityCouponByCommodityName", method = RequestMethod.GET)
    @ApiOperation("根据名称搜索商品优惠券")
    @ResponseBody
    public Result selectByUserId(int page,String commodityName,int sort) {
        int page1;
        if(page%3==0){
            page1=page/3;
        }else{
            page1=(page/3)+1;
        }
        DecimalFormat formater = new DecimalFormat();
        formater.setMaximumFractionDigits(2);
        formater.setGroupingSize(0);
        formater.setRoundingMode(RoundingMode.FLOOR);
        List<CommodityCoupon> list=new ArrayList<>();


        CommonInfo one = commonRepository.findOne(10);
        //淘宝
        list=getTaaoBao(list,one,commodityName,sort,page1,formater);
        //淘宝拉取的数据长度
        int tao=list.size();
        //clientId
        CommonInfo clientId = commonRepository.findOne(23);
        CommonInfo clientSecret = commonRepository.findOne(24);
        //拼多多
       list=getPdd(list,clientId,clientSecret,commodityName,sort,page1,formater);
        //拼多多拉取的数据
        int pdd=list.size()-tao;
        CommonInfo three = commonRepository.findOne(30);
        list=getJD(list,three,commodityName,page1);
        //京东拉取的数据
        int jd=list.size()-tao-pdd;
        //判断数据长度是否足够
        if(list.size()<30){
            //数据不足则继续拉取
            int pages=page1+1;
            boolean taoBao=true;
            boolean pinDuoDuo=true;
            boolean jingDong=true;
            if(tao<10){
                taoBao=false;
            }
            if(pdd<10){
                pinDuoDuo=false;
            }
            if(jd<10){
                jingDong=false;
            }
            while (true){
                //尝试从淘宝拉取数据
                if(taoBao){
                    int size1 = list.size();
                    list=getTaaoBao(list,one,commodityName,sort,pages,formater);
                    if(list.size()>=30){
                        break;
                    }
                    int size2 = list.size()-size1;
                    //淘宝拉取数据小于10 则淘宝数据已经拉取完
                    if(size2<10){
                        taoBao=false;
                    }
                }

                if(pinDuoDuo){
                    int size1 = list.size();
                    list=getPdd(list,clientId,clientSecret,commodityName,sort,page,formater);
                    if(list.size()>=30){
                        break;
                    }
                    int size2 = list.size()-size1;
                    //拼多多拉取数据小于10 则拼多多数据已经拉取完
                    if(size2<10){
                        pinDuoDuo=false;
                    }
                }
                if(jingDong){
                    int size1 = list.size();
                    list=getJD(list,three,commodityName,page);
                    if(list.size()>=30){
                        break;
                    }
                    int size2 = list.size()-size1;
                    //京东拉取数据小于10 则京东数据已经拉取完
                    if(size2<10){
                        jingDong=false;
                    }
                }

                //当京东淘宝数据都拉取完后数据仍然不足 则证明商品已经拉取完 直接返回
                if(!jingDong && !taoBao && !pinDuoDuo){
                    break;
                }
                pages++;
            }
        }


        //排序
        int finalSort = sort;
        Collections.sort(list, new Comparator<CommodityCoupon>() {
            @Override
            public int compare(CommodityCoupon o1, CommodityCoupon o2) {
                switch (finalSort) {
                    case 2://根据销量进行排序
                        String o1str=o1.getItemsale();
                        String o2str=o2.getItemsale();
                        Integer o1sale,o2sale;
                        boolean o1bool = o1.getItemsale().contains("万");
                        if(o1bool){
                            o1str=o1.getItemsale().substring(0, o1.getItemsale().indexOf("万"));
                            Double o1double=Double.parseDouble(o1str)*10000;
                            o1sale=o1double.intValue();
                        }else{
                            o1sale=Integer.parseInt(o1str);
                        }
                        boolean o1boo2 = o2.getItemsale().contains("万");
                        if(o1boo2){
                            o2str=o2.getItemsale().substring(0, o2.getItemsale().indexOf("万"));
                            Double o2double=Double.parseDouble(o2str)*10000;
                            o2sale=o2double.intValue();
                        }else{
                            o2sale=Integer.parseInt(o2str);
                        }
                        if(o1sale>o2sale){
                            return -1;
                        }else{
                            return 1;
                        }

                    case 1://综合 根据返回的数据优惠券大小时间进行排序
                        if(Double.parseDouble(o1.getCouponmoney())>Double.parseDouble(o2.getCouponmoney())){
                            return -1;
                        }else if(Double.parseDouble(o1.getCouponmoney())<Double.parseDouble(o2.getCouponmoney())){
                            return 1;
                        }else{
                            if(Long.parseLong(o1.getCouponstarttime())>Long.parseLong(o2.getCouponstarttime())){
                                return -1;
                            }else{
                                return 1;
                            }
                        }

                    case 0://最新按照返回的数据根据时间排序
                        if(Long.parseLong(o1.getCouponstarttime())>Long.parseLong(o2.getCouponstarttime())){
                            return -1;
                        }else{
                            return 1;
                        }
                    case 6://最高佣金进行排序
                        if(Double.parseDouble(o1.getTkmoney())>Double.parseDouble(o2.getTkmoney())){
                            return -1;
                        }else if(Double.parseDouble(o1.getTkmoney())<Double.parseDouble(o2.getTkmoney())){
                            return 1;
                        }else{
                            if(Long.parseLong(o1.getCouponstarttime())>Long.parseLong(o2.getCouponstarttime())){
                                return -1;
                            }else{
                                return 1;
                            }
                        }
                    case 4://最低价格排序
                        if( Double.parseDouble(o1.getItemendprice())>Double.parseDouble((o2.getItemendprice()))){
                            return 1;
                        }else if(Double.parseDouble(o1.getItemendprice())<Double.parseDouble((o2.getItemendprice()))){
                            return -1;
                        }else{
                            if(Long.parseLong(o1.getCouponstarttime())>Long.parseLong(o2.getCouponstarttime())){
                                return -1;
                            }else{
                                return 1;
                            }
                        }
                    default:
                        return 0;
                }

            }
        });

        //根据当前页数进行判断返回数据
        if(page%3==0){
            //返回数据前判断 集合长度是否足够
            if(list.size()>20){
                return ResultUtil.success(list.subList(20,list.size()));
            }else{
                return ResultUtil.success();
            }
        }else{
            if((page+2)%3==0){
                if(list.size()>0){
                    return ResultUtil.success(list.subList(0,list.size()>10?10:list.size()));
                }else{
                    return ResultUtil.success();
                }
            }else{
                if(list.size()>10){
                    return ResultUtil.success(list.subList(10,list.size()>20?20:list.size()));
                }else{
                    return ResultUtil.success();
                }
            }

        }
    }


    private List<CommodityCoupon> getTaaoBao(List<CommodityCoupon> list,CommonInfo one,String commodityName,Integer sort,Integer page,DecimalFormat formater){
        RestTemplate restTemplate = new RestTemplate();
        String uri = "https://tk.gomyorder.cn/api/supersearch/apikey/"+one.getValue()+"/keyword/"+commodityName+"/back/10/sort/"+sort+"/min_id/"+page+"/is_coupon/1/tb_p/"+page;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
        Integer code = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class).getStatusCodeValue();
        if (code == 200) {
            String strbody = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class).getBody();
            Map<String,Object> map=(Map) JSON.parse(strbody);
            Integer code1 = Integer.parseInt(map.get("code").toString());
            if(1==code1){
                String jsonData = map.get("data").toString();
                JSONArray jsonArray = JSON.parseArray(jsonData);
                for(int i=0;i<jsonArray.size();i++){
                    try {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        CommodityCoupon commodityCoupon=new CommodityCoupon();
                        commodityCoupon.setClassify(1);//分类 1淘宝 2京东 3拼多多
                        commodityCoupon.setCouponendtime(jsonObject.getString("couponendtime"));
                        commodityCoupon.setCouponstarttime(jsonObject.getString("couponstarttime"));
                        commodityCoupon.setCouponmoney(jsonObject.getString("couponmoney"));
                        commodityCoupon.setItemendprice(jsonObject.getString("itemendprice"));
                        commodityCoupon.setItemid(jsonObject.getLong("itemid"));
                        commodityCoupon.setItempic(jsonObject.getString("itempic"));
                        commodityCoupon.setItemsale(jsonObject.getString("itemsale"));
                        commodityCoupon.setItemtitle(jsonObject.getString("itemtitle"));
                        commodityCoupon.setShopname(jsonObject.getString("shopname"));
                        //计算佣金  淘宝计算方式   （ tkrates * 0.01 ） * itemendprice
                        Double tkrates = jsonObject.getDouble("tkrates");
                        Double itemendprice = jsonObject.getDouble("itemendprice");
                        Double mul = AmountCalUtils.mul(tkrates, 0.01);
                        mul = AmountCalUtils.mul(mul, itemendprice);
                        commodityCoupon.setTkmoney(formater.format(mul));
                        list.add(commodityCoupon);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
        return list;
    }


    private List<CommodityCoupon> getPdd(List<CommodityCoupon> list,CommonInfo clientId,CommonInfo clientSecret,String commodityName,Integer sort,Integer page,DecimalFormat formater){
        PddDdkGoodsSearchResponse response = null;
        try {
            PopClient client = new PopHttpClient(clientId.getValue() != null ? clientId.getValue() : Config.clientId, clientSecret.getValue() != null ? clientSecret.getValue() : Config.clientSecret);
            PddDdkGoodsSearchRequest request = new PddDdkGoodsSearchRequest();
            if (commodityName != null) {
                request.setKeyword(commodityName);
            }
            request.setPage(page);
            request.setPageSize(10);
            switch (sort){
                case 2: request.setSortType(6);break;
                case 0: request.setSortType(0);break;
                case 1: request.setSortType(12);break;
                case 6: request.setSortType(14);break;
                case 4: request.setSortType(9);break;
                default:
            }
            request.setWithCoupon(true);
            PddDdkGoodsSearchResponse pddDdkGoodsSearchResponse = client.syncInvoke(request);
            PddDdkGoodsSearchResponse.GoodsSearchResponse goodsSearchResponse = pddDdkGoodsSearchResponse.getGoodsSearchResponse();
            if( goodsSearchResponse !=null &&  goodsSearchResponse.getGoodsList().size()>0){
                List<PddDdkGoodsSearchResponse.GoodsSearchResponseGoodsListItem> goodsList = goodsSearchResponse.getGoodsList();
                for(PddDdkGoodsSearchResponse.GoodsSearchResponseGoodsListItem goodsListItem:goodsList){
                    try {
                        CommodityCoupon commodityCoupon=new CommodityCoupon();
                        commodityCoupon.setClassify(3);//分类 1淘宝 2京东 3拼多多
                        commodityCoupon.setCouponendtime(goodsListItem.getCouponEndTime().toString());
                        commodityCoupon.setCouponstarttime(goodsListItem.getCouponStartTime().toString());
                        commodityCoupon.setCouponmoney(AmountCalUtils.divide(Double.parseDouble(goodsListItem.getCouponDiscount().toString()),100).toString());
                        Long money=goodsListItem.getMinGroupPrice()-goodsListItem.getCouponDiscount();
                        commodityCoupon.setItemendprice(AmountCalUtils.divide(Double.parseDouble(money.toString()),100).toString());
                        commodityCoupon.setItemid(goodsListItem.getGoodsId());
                        commodityCoupon.setItempic(goodsListItem.getGoodsImageUrl());
                        commodityCoupon.setItemsale(goodsListItem.getSalesTip());
                        commodityCoupon.setItemtitle(goodsListItem.getGoodsName());
                        commodityCoupon.setShopname(goodsListItem.getMallName());
                        //计算佣金  拼多多计算方式   （ minGroupPrice - couponDiscount ） *  0.01 * （ promotionRate * 0.001 ）
                        Long minGroupPrice = goodsListItem.getMinGroupPrice();
                        Long couponDiscount = goodsListItem.getCouponDiscount();
                        Double promotionRate = Double.parseDouble(goodsListItem.getPromotionRate().toString());
                        minGroupPrice=minGroupPrice-couponDiscount;
                        Double mul = AmountCalUtils.mul(promotionRate, 0.001);
                        mul=AmountCalUtils.mul(mul,AmountCalUtils.mul(minGroupPrice,0.01));
                        commodityCoupon.setTkmoney(formater.format(mul));
                        list.add(commodityCoupon);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    private List<CommodityCoupon> getJD(List<CommodityCoupon> list,CommonInfo three,String commodityName,Integer page){
        //京东
        try {

            String apkey = Config.MIAOYOUQUN_Key;
            if (three != null) {
                apkey = three.getValue();
            }
            String word = URLEncoder.encode(commodityName, "utf-8");
            String url = Config.MIAOYOUQUN_URL + "/jingdong/getJdUnionItems?apkey=" + apkey + "&pageIndex=" + page + "&pageSize=10&isCoupon=1&sort=desc&keyword=" + word + "&sortName=" + 5;
            String s = HttpClient.doGet(url);
            JSONObject body = JSON.parseObject(s);
            Integer code1 = body.getInteger("code");
            if(200==code1){
                JSONObject data = body.getJSONObject("data");
                JSONArray jsonArray = data.getJSONArray("list");
                for(int i=0;i<jsonArray.size();i++){
                    try{
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        CommodityCoupon commodityCoupon=new CommodityCoupon();
                        commodityCoupon.setClassify(2);//分类 1淘宝 2京东 3拼多多
                        JSONObject couponInfo = jsonObject.getJSONObject("couponInfo");
                        JSONArray couponList = couponInfo.getJSONArray("couponList");
                        Long getEndTime = couponList.getJSONObject(0).getLong("getEndTime")/100;
                        Long getStartTime = couponList.getJSONObject(0).getLong("getStartTime")/100;
                        String discount = couponList.getJSONObject(0).getString("discount");
                        commodityCoupon.setCouponendtime(getEndTime.toString());
                        commodityCoupon.setCouponstarttime(getStartTime.toString());
                        commodityCoupon.setCouponmoney(discount);
                        JSONObject priceInfo = jsonObject.getJSONObject("priceInfo");
                        String lowestCouponPrice = priceInfo.getString("lowestCouponPrice");
                        commodityCoupon.setItemendprice(lowestCouponPrice);
                        commodityCoupon.setItemid(jsonObject.getLong("skuId"));
                        JSONObject imageInfo = jsonObject.getJSONObject("imageInfo");
                        JSONArray imageList = imageInfo.getJSONArray("imageList");
                        String url1 = imageList.getJSONObject(0).getString("url");
                        commodityCoupon.setItempic(url1);
                        commodityCoupon.setItemsale(jsonObject.getString("inOrderCount30Days"));
                        commodityCoupon.setItemtitle(jsonObject.getString("skuName"));
                        JSONObject shopInfo = jsonObject.getJSONObject("shopInfo");
                        String shopName = shopInfo.getString("shopName");
                        commodityCoupon.setShopname(shopName);
                        //计算佣金  京东 直接取值 不用计算
                        JSONObject commissionInfo = jsonObject.getJSONObject("commissionInfo");
                        String couponCommission = commissionInfo.getString("couponCommission");
                        if(StringUtils.isNotBlank(couponCommission)){
                            commodityCoupon.setTkmoney(couponCommission);
                        }else{
                            commodityCoupon.setTkmoney("0.00");
                        }
                        list.add(commodityCoupon);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return list;
    }




}
